using UserService.Domain.Entities;
using UserService.Domain.Events;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using Volo.Abp.EventBus.Distributed;

namespace UserService.Domain.Managers;

/// <summary>
/// 用户管理器 - 领域服务
/// </summary>
public class UserManager : DomainService
{
    private readonly IRepository<UserAggregateRoot, Guid> _userRepository;
    private readonly IDistributedEventBus _distributedEventBus;
        
    public UserManager(
        IRepository<UserAggregateRoot, Guid> userRepository,
        IDistributedEventBus distributedEventBus)
    {
        _userRepository = userRepository;
        _distributedEventBus = distributedEventBus;
    }
        
    /// <summary>
    /// 创建新用户并发布领域事件
    /// </summary>
    public async Task<UserAggregateRoot> CreateAsync(
        string userName,
        string nickName,
        string email,
        string phoneNumber,
        string password)
    {
        // 检查用户名是否已存在
        var existingUser = await _userRepository.FirstOrDefaultAsync(u => u.UserName == userName);
        if (existingUser != null)
        {
            // TODO throw new UserAlreadyExistsException(userName);
        }
            
        // 生成ID (这里可以使用雪花ID等分布式ID生成器)
        var id = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0);
            
        // 创建用户
        var user = new UserAggregateRoot( userName, nickName, email, phoneNumber, password);
        user.BuildPassword();
        
        // 保存用户
        await _userRepository.InsertAsync(user);
            
        // 发布用户创建事件
        await _distributedEventBus.PublishAsync(new UserCreatedEvent(user));
            
        return user;
    }
        
    // 其他用户管理方法...
}